var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');
var cheerio = require('cheerio');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;

function fn1(typeId, initial) {
    var artistList = [];
    var url = `https://music.163.com/discover/artist/cat?id=${typeId}&initial=${initial}`;
    console.log(url);

    superagent
        .get(url)
        .end(function (err, res) {
            let content = res.res.text;
            let $ = cheerio.load(content);

            let list = $('.m-sgerlist>ul>li .s-fc0');
            // console.log(list.length);

            let values = []
            list.each((i, ele) => {
                let element = list.eq(i);
                // 歌手名
                let name = element.text();
                // console.log(name);
                let id = element.attr().href.replace(/.*id./g, '');
                let cat = typeId;
                let value;
                if (initial === -1) {
                    value = [id, name, cat, 1];
                } else {
                    value = [id, name, cat];
                }
                values.push(value);

            });
            console.log(values);

            let connection = mysql.createConnection(mysqlCloudMusic);

            let queryString;
            if (initial === -1) {
                queryString = `insert ignore into artist(id,name,cat,hot) values ?`;

            } else {
                queryString = `insert ignore into artist(id,name,cat) values ?`;

            }
            connection.query(queryString, [values], function (error, results) {
                if (error) {
                    console.log(error);
                }
                if (results) {
                    console.log('inserted');
                    console.log();
                    if (initial > 0 && initial < 90) {
                        initial += 1;
                        setTimeout(() => {
                            fn1(typeId, initial);
                        }, 500);
                    } else {
                        console.log(typeId + ' end');

                    }
                }

            })
            connection.end();
        })
}

var typeList = [
    1001, 1002, 1003,
    2001, 2002, 2003,
    6001, 6002, 6003,
    7001, 7002, 7003,
    4001, 4002, 4003
];

for (var i = 0; i < 15; i++) {
    (function (i) {
        setTimeout(() => {
            console.log(typeList[i]);
            // fn1(typeList[i], 0);
            // fn1(typeList[i], -1);
            fn1(typeList[i], 65);

        }, 1000 * i);
    })(i);
}